<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <div>
      <el-form label-width="100px" :model="pwd" :rules="reRules" ref="formRef">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input type="password" v-model="pwd.old_pwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input type="password" v-model="pwd.new_pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input type="password" v-model="pwd.re_pwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePwd">确认修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/user'
export default {
  data() {
    const validatePass1 = (rule, value, callback) => {
      // 新密码输入框使用了这个规则，所以value表示输入的新密码
      if (value === this.pwd.old_pwd) {
        callback(new Error('新密码不能与原密码一致'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      // 确认密码使用了这个规则，所以value表示输入框的确认密码
      if (value === this.pwd.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      pwd: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      reRules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: validatePass1, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updatePwdAPI(this.pwd)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 业务逻辑一：修改密码成功后，重置表单
          // this.$refs.formRef.resetFields()
          // 业务逻辑二：修改密码后，退出，重新登陆
          this.$store.commit('user/updateToken', '')
          this.$store.commit('user/updateUser', {})
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 重置
    reset() {
      // 清空表单
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
}
.el-form {
  width: 500px;
}
</style>
